package com.heima.account.action.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.account.action.AccountAction;
import com.heima.account.entity.Account;
import com.heima.account.entity.AccountFreeze;
import com.heima.account.service.IAccountFreezeService;
import com.heima.account.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TODO:TCC模式的实现类
 */
@Service
public class AccountActionImpl implements AccountAction {

    @Autowired
    private IAccountFreezeService freezeService;

    @Autowired
    private IAccountService accountService;

    @Override
    public void deduct(Integer userId, Integer money) {
        // todo:记录冻结金额到冻结表中
        AccountFreeze freeze = new AccountFreeze();
        String xid = RootContext.getXID();
        freeze.setXid(xid);
        freeze.setUserId(userId);
        freeze.setFreezeMoney(money);
        // todo:保存数据库
        freezeService.save(freeze);
        // todo:扣减当前账户表的金额
        LambdaUpdateWrapper<Account> update = new LambdaUpdateWrapper<>();
        update.eq(Account::getUserId, userId);
        update.setSql("money = money -" + money);
        accountService.update(update);
    }

    @Override
    public boolean confirm(BusinessActionContext context) {
        String xid = context.getXid();
        // todo:根据xid删除冻结记录
        LambdaQueryWrapper<AccountFreeze> query = new LambdaQueryWrapper<>();
        query.eq(AccountFreeze::getXid, xid);
        freezeService.remove(query);
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext context) {
        String xid = context.getXid();
        // todo:根据xid删除冻结记录
        LambdaQueryWrapper<AccountFreeze> query = new LambdaQueryWrapper<>();
        query.eq(AccountFreeze::getXid, xid);
        AccountFreeze one = freezeService.getOne(query);
        freezeService.remove(query);
        // todo:冻结金额添加回账户表中
        if (one != null) {
            Integer freezeMoney = one.getFreezeMoney();
            LambdaUpdateWrapper<Account> update = new LambdaUpdateWrapper<>();
            update.eq(Account::getUserId, one.getUserId());
            update.setSql("money = money +" + freezeMoney);
            accountService.update(update);
        }
        return true;
    }
}
